#include "stdafx.h"
#include "Bias.h"
#include <exception>

//--------------------------------------------------------------------------------
TimeZone::Bias::Bias(int tz_index)
	: m_tz_index(tz_index)
	, m_cached_bias_sec(0)
	, m_cache_is_valid(false)
{}
//--------------------------------------------------------------------------------
TimeZone::Bias::~Bias()
{}
//--------------------------------------------------------------------------------
int TimeZone::Bias::biasSeconds(const Time& local_time)
{
	if (m_cache_is_valid && m_started_at <= local_time && local_time < m_expired_at)
	{}
	else
	{
		_reload(local_time);
	}

	return m_cached_bias_sec;
}
//--------------------------------------------------------------------------------
int TimeZone::Bias::biasSeconds(int utc)
{
	if (m_cache_is_valid && m_started_at_utc <= utc && utc < m_expired_at_utc)
	{}
	else
	{
		_reload(utc);
	}

	return m_cached_bias_sec;
}
//--------------------------------------------------------------------------------
void TimeZone::Bias::_reload(const Time& local_time)
{
	m_cache_is_valid = false;

	if (!TimeZone::getZone(m_tz_index, &m_tz))
	{
		char buffer[1024];
		sprintf_s(buffer, sizeof(buffer)/sizeof(buffer[0]), "Failed to load time zone with index %d", m_tz_index);
		throw std::exception(buffer);
	}

	m_cached_bias_sec = m_tz.biasMinutes(local_time, &m_started_at, &m_expired_at) * 60;

	m_cache_is_valid = true;
}
//--------------------------------------------------------------------------------
void TimeZone::Bias::_reload(int utc)
{
	m_cache_is_valid = false;

	if (!TimeZone::getZone(m_tz_index, &m_tz))
	{
		char buffer[1024];
		sprintf_s(buffer, sizeof(buffer)/sizeof(buffer[0]), "Failed to load time zone with index %d", m_tz_index);
		throw std::exception(buffer);
	}

	m_cached_bias_sec = m_tz.biasSeconds(utc, &m_started_at_utc, &m_expired_at_utc);

	m_cache_is_valid = true;
}
